package test;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.junit.After;
import org.junit.Before;

import com.google.appengine.api.datastore.dev.LocalDatastoreService;
import com.google.appengine.tools.development.ApiProxyLocalImpl;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.ApiProxy.ApiProxyException;
import com.google.apphosting.api.ApiProxy.Environment;
import com.google.apphosting.api.ApiProxy.LogRecord;

public abstract class BaseTestCase {

    protected static class MyDelegate extends ApiProxyLocalImpl {

        MyDelegate(File folder) {
            super(folder);
        }

        public byte[] makeSyncCall(Environment environment, String packageName,
                String methodName, byte[] request) throws ApiProxyException {
            if (packageName.equals("datastore_v3")) {
                System.out.println("makeSyncCall:" + packageName + ":"
                        + methodName);
            }
            return super.makeSyncCall(environment, packageName, methodName,
                    request);
        }

        public void log(Environment environment, LogRecord logRecord) {
            super.log(environment, logRecord);
        }
    }

    @Before
    public void setup() {
        ApiProxy.setEnvironmentForCurrentThread(new ApiProxy.Environment() {
            public String getAppId() {
                return "unit test";
            }

            public Map<String, Object> getAttributes() {
                return new HashMap<String, Object>();
            }

            public String getAuthDomain() {
                return "gmail.com";
            }

            public String getEmail() {
                return "hoge@gmail.com";
            }

            public String getRequestNamespace() {
                return "";
            }

            public String getVersionId() {
                return "1";
            }

            public boolean isAdmin() {
                return false;
            }

            public boolean isLoggedIn() {
                return true;
            }
        });
        ApiProxy
                .setDelegate(new MyDelegate(new File("target/lowLevelApiTest")) {
                });
        ApiProxyLocalImpl proxy = (ApiProxyLocalImpl) ApiProxy.getDelegate();
        proxy.setProperty(LocalDatastoreService.NO_STORAGE_PROPERTY,
                Boolean.TRUE.toString());
    }

    @After
    public void tearDown() {
        ApiProxyLocalImpl proxy = (ApiProxyLocalImpl) ApiProxy.getDelegate();
        LocalDatastoreService datastoreService = (LocalDatastoreService) proxy
                .getService("datastore_v3");
        datastoreService.clearProfiles();
        ApiProxy.setDelegate(null);
        ApiProxy.setEnvironmentForCurrentThread(null);
    }

}
